package com.nage.multiplayer;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.util.Log;

public class MultiplayerOutputThread extends Thread {

	MultiplayerSystem ms;
	BufferedOutputStream out;
	ArrayList<byte[]> temp;
	boolean connected;

	public MultiplayerOutputThread(MultiplayerSystem ms) {
		this.ms = ms;
		try {
			out = new BufferedOutputStream(
					ms.m_Socket.getOutputStream());
			connected = true;
			Log.i("MultiplayerOutputThread", "OutputStream connected");

		} catch (IOException e) {
			Log.e("MultiplayeOutputThread", "Cannot find remote connection: "+e.getMessage());
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public void run() {

		while (connected) {
	//		Log.d("MultiplayerOutputThread", "Examinging outputBuffer...");
			if (!ms.outputBuffer.isEmpty()) {
				// Log.d("MultiplayerOutputThread",
				// "Sending packets from outputBuffer.");
				synchronized (ms.outputBuffer) {
					temp = (ArrayList<byte[]>) ms.outputBuffer.clone();
					ms.outputBuffer.clear();
				}
				try {
					int i = 0;
					for (byte[] p : temp) {
					//	Log.d("MultiplayerOutputThread", "Trying to send "+p.length+" bytes");
						out.write(p);
						i++;
					}
					out.flush();
					//Log.d("MultiplayerOutputThread", "Sent "+i+" packets.");
				} catch (Exception e) {
					Log.e("MultiplayerOutputThread", "Problem sending packet. Be careful!");
				}

			} else {
				synchronized (this) {
					try {
				//		Log.d("MultiplayerOutputThread",
				//				"outputBuffer empty. Waiting for notification");
						wait();
				//		Log.d("MultiplayerOutputThread", "Recieved notify - something in buff? lets see...");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}

		}

	}

	public void close() {
		connected = false;
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
